<?php
/**
 *Telegram @cocolive9 2023/9/25 16:12
 */


namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Db;
use think\Validate;

/**
 * 会员接口
 */
class Wxpay extends Api
{

    protected $noNeedLogin = ['*'];

    public function _initialize()
    {

        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }



    /**
     * 微信支付
     */
    public function paysone()
    {


        $id=$this->request->param('id');
        $user=$this->auth->getUser();

        $userinf=Db::name('user')->where(['id'=>$user['id']])->find();

        $appid = 'wxcf7642e21d43e8f9';
        $mch_id = '1672597421';
        $key = 'D1qJMTjUvsOQRetbmKyCnI4BEaGV2Wrg'; //32位字符

        $nonce_str = 'one' . date('Ymdhis') . rand(100, 999);

        $money=Db::name('moneyset')->find();
        $zfmoney=$money['ones'];

        //注意 这里应该要保存下信息  方便回调验证
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';

        $parameters = array(
            'appid' => $appid, //服务商ID
            'mch_id' => $mch_id, //商户号
            'nonce_str' => $nonce_str, //随机字符串
            'body' => '单次',
            'out_trade_no' => $nonce_str,
            'total_fee' => $zfmoney * 100, //分
            'spbill_create_ip' => $_SERVER['REMOTE_ADDR'], //终端IP
            'notify_url' => 'http://' . $_SERVER['HTTP_HOST'] . '/api/wxpay/paybackc',  //回调
            'openid' => $userinf['openid'], //用户openid
            'trade_type' => 'JSAPI'//交易类型
        );

        $logs['user_id']=$user['id'];
        $logs['land_id']=$id;
        $logs['times']=time();
        $logs['payorder']=$nonce_str;

        Db::name('land_pay')->data($logs)->insert();

        //统一下单签名
        $parameters['sign'] = getSign($parameters, $key);
        $xmlData = arrayToXml($parameters);
        $return = xmlToArray(postXmlCurl($xmlData, $url, 60));




        if (!isset($return['result_code'])){
            $this->error($return['return_msg']);
        }

        $parameter = array(
            'appId' => $appid, //小程序ID
            'timeStamp' =>time().'', //时间戳
            'nonceStr' => $nonce_str, //随机串
            'package' => 'prepay_id=' . $return['prepay_id'], //数据包
            'signType' => 'MD5'//签名方式
        );
        //签名
        $parameter['paySign'] = getSign($parameter, $key);


        $this->success('支付信息', $parameter);


    }

    /**
     * 微信支付 开通会员
     */
    public function paymonth()
    {

        $icon=$this->request->param('icon');
        $user=$this->auth->getUser();
        $userinf=Db::name('user')->where(['id'=>$user['id']])->find();


        $appid = 'wxcf7642e21d43e8f9';
        $mch_id = '1672597421';
        $key = 'D1qJMTjUvsOQRetbmKyCnI4BEaGV2Wrg'; //32位字符

        $nonce_str = 'vip' . date('Ymdhis') . rand(100, 999);


        $money=Db::name('moneyset')->find();

        if ($icon==2){
            $zfmoney = $money['year'];
        }else{
            $zfmoney = $money['month'];
        }


        //注意 这里应该要保存下信息  方便回调验证
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';

        $parameters = array(
            'appid' => $appid, //服务商ID
            'mch_id' => $mch_id, //商户号
            'nonce_str' => $nonce_str, //随机字符串
            'body' => '开通会员',
            'out_trade_no' => $nonce_str,
            'total_fee' => $zfmoney * 100, //分
            'spbill_create_ip' => $_SERVER['REMOTE_ADDR'], //终端IP
            'notify_url' => 'https://bantonggou.vipwjf.com/api/wxpay/paybacka',  //回调
            'openid' => $userinf['openid'], //用户openid
            'trade_type' => 'JSAPI'//交易类型
        );

        $logs['user_id']=$user['id'];
        $logs['types']=$icon;
        $logs['money']=$zfmoney;
        $logs['times']=time();
        $logs['payorder']=$nonce_str;

        Db::name('pay_vip')->data($logs)->insert();

        //统一下单签名
        $parameters['sign'] = getSign($parameters, $key);
        $xmlData = arrayToXml($parameters);
        $return = xmlToArray(postXmlCurl($xmlData, $url, 60));

        if (!isset($return['result_code'])){
            $this->error($return['return_msg']);
        }

        $parameter = array(
            'appId' => $appid, //小程序ID
            'timeStamp' =>time().'', //时间戳
            'nonceStr' => $nonce_str, //随机串
            'package' => 'prepay_id=' . $return['prepay_id'], //数据包
            'signType' => 'MD5'//签名方式
        );
        //签名
        $parameter['paySign'] = getSign($parameter, $key);


        $this->success('支付信息', $parameter);


    }

    //支付回调
    public function paybackc(){

        $input=file_get_contents("php://input");

        $obj = simplexml_load_string($input, 'SimpleXMLElement', LIBXML_NOCDATA);

        $data = json_decode(json_encode($obj), true);


        $payorder=$data['out_trade_no'];

        $log=Db::name('land_pay')->where(['payorder'=>$payorder])->where(['status'=>0])->find();


        if ($log){

            Db::name('land_pay')->where(['payorder'=>$payorder])->update(['status'=>1]);

        }

    }

    //支付回调
    public function paybacka(){

        $input=file_get_contents("php://input");

        Db::name('paylogs')->data(['text'=>$input,'date'=>date('y-m-d H:i:s')])->insert();

        $obj = simplexml_load_string($input, 'SimpleXMLElement', LIBXML_NOCDATA);



        $data = json_decode(json_encode($obj), true);


        $payorder=$data['out_trade_no'];

        Db::name('paylogs')->data(['text'=>$payorder,'date'=>date('y-m-d H:i:s')])->insert();


        $log=Db::name('pay_vip')->where(['payorder'=>$payorder])->where(['status'=>0])->find();


        if ($log){

            Db::name('pay_vip')->where(['payorder'=>$payorder])->update(['status'=>1]);

            $uplod['level']=2;
            $user=Db::name('user')->where(['id'=>$log['user_id']])->find();

            $now=time();

            $btime=$now>$user['viper_time']?time():$user['viper_time'];

            if ($log['types']==1){
                $uplod['viper_time']=$btime+2592000;
            }else{
                $uplod['viper_time']=$btime+31104000;
            }


            Db::name('user')->where(['id'=>$log['user_id']])->update($uplod);

        }

    }




}